//
//  BoardViewController.m
//  CheckersGame
//
//  Created by  on 11-11-23.
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

#import "BoardViewController.h"
#import "Piece.h"

@implementation BoardViewController

@synthesize toplevelView;
@synthesize boardView;

-(void)synchToGameState : (CheckersGameState*) game {
    CheckersMove move;
	if (pieceArray){    
		for (Piece* piece in pieceArray){
			[piece removeFromSuperview];
		}
		pieceArray = nil;
	} 
    boardView.gameState = game;
    [boardView setNeedsDisplay];
    pieceArray = [Piece pieceArrayFromBoard: game View: boardView];
    for (Piece* piece in pieceArray){
        [self.toplevelView addSubview: piece];
    }
}

-(void) attemptNextMove {
    if (!timer) return;
    CheckersMove move;
    int game_result;
    if (gameState.moveAmount >= MAX_CHECKERS_GAME-1){
        NSLog(@"Game has drawn!");
        [self.navigationController popViewControllerAnimated:YES];
    }
        
    if (chbIsGameOver([gameState getBoardRef], &game_result)){
        NSLog(@"Player %d has won", game_result);

        [self.navigationController popViewControllerAnimated:YES];
    } else if ( [[gameState currentPlayer] decideMove: &move Board: [gameState getBoardRef]] ) {
        [gameState makeMove: &move];
        [self synchToGameState: gameState];
        [boardView setNeedsDisplay];
    } 
}

-(void)gameLoop {
    [self attemptNextMove];
}

-(IBAction)didClickBoard : (id)sender{
    gameState.pieceIsSelected = NO;
}


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        //self.wantsFullScreenLayout = YES;
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}


// Controller was sent message for a new game
- (void)newGame : (CheckersGameState*) gs
{
	gameState = gs;
	[self synchToGameState: gameState];
}

// Controller was sent message for a quit
- (IBAction)quit:(id)sender
{
    [self.navigationController popToRootViewControllerAnimated:YES];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
   // [self newGame];
    //[self.navigationController setNavigationBarHidden:YES animated:YES];
    // Do any additional setup after loading the view from its nib.
    
    timer = [NSTimer scheduledTimerWithTimeInterval:0.033 target:self 
                                           selector:@selector(gameLoop) 
                                           userInfo:nil repeats:YES];
    
}
- (void)viewDidDisappear:(BOOL)animated {
    [timer invalidate];
    timer = nil;
    gameState = nil;
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter]; 
    [center removeObserver: self];
}
- (void)viewDidUnload
{
    [super viewDidUnload];
    
    //[self.navigationController setNavigationBarHidden:NO animated:YES];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


-(IBAction)didSelectUndo: (id)sender {
    [gameState unmakeMove];
    [self synchToGameState:gameState];
}

-(IBAction)didSelectPause: (id)sender{
    UIButton* but = (UIButton*) sender;
    
    [gameState togglePauseState];
    if (gameState.isPaused)
        [but setTitle: @"Go" forState:UIControlStateNormal];
    else 
        [but setTitle: @"Pause" forState:UIControlStateNormal];
        
}

@end
